import { pipe, tap } from 'ramda';
import { setUpApp } from './config/middlewares';
import { initDB } from "./infrastructure/db";
import { logUtil } from "./infrastructure/logutil";
import env from './config/env';
import { startRedis, initSocketIo } from './infrastructure/redis';
const { map, chain } = require('pointfree-fantasy');
const Task = require('data.task');
const http = require('http');
const sockectio = require('socket.io');
import { publish } from "./infrastructure/bus";

const startUp: any = pipe(
    () => new Task((rej, res) => initDB().then(res).catch(rej)),
    chain(setUpApp),
    chain(app => new Task((rej, res) => {
        var server = http.createServer(app);
        var io = sockectio(server);
        initSocketIo(io);
        server.listen(env.app.port, () => {
            logUtil.info(`Express: listening on ${env.app.port}`);
            res(app);
        })
    })),
    chain(() => publish('WECHAT_START', {}))
);

logUtil.info('------服务启动中------')
startUp()
    .fork(e => {
        logUtil.error('app start err\n', e)
        logUtil.info('------服务启动结束------')
    }, v => {
        logUtil.info('app start success')
        logUtil.info('------服务启动结束------')
        if (process.send) {
            process.send('ready');
        }
    });
startRedis()
    .fork(e => {
        logUtil.error('redis start err\n', e)
        logUtil.info('------redis启动结束------')
    }, v => {
        logUtil.info('redis start success')
        logUtil.info('------redis启动结束------')
    });



process.on('uncaughtException', (e) => {
    logUtil.fatal(`uncaughtException: ${e}`)
})//未捕获的系统异常

process.on('unhandledRejection', (e) => {
    logUtil.fatal(`unhandledRejection: ${e}`)
})//未捕获的promise异常

